#!/usr/bin/env python3
# whoareu.py

import sys, pickle, socket, pwd
sys.path.insert(0, r'/home/george/Projects/ISH')
import dialog
from gi.repository import Gtk

# A collection of routines to prefill the dialog box.
class Prefill:
    def get_hostname():
        hostname = socket.gethostname()
        if hostname: return hostname
        else: return ''

# If gecos is not needed, use dialog.get_username()
    def get_username():
        user = dialog.get_username()
        userentry = pwd.getpwnam(user)
        userfield = userentry[4] # gecos
# Tre komma efter namn i gecos ??? Funkar detta med ldap?
        usernam = userfield.split(",")
        username = usernam[0]
        if username: return username
        else: return ''

# Main class, handles all user input and more.
class Handler:
    # Exit app if windows is closed. Traps the signal from GUI.
    def on_window1_destroy(self, *args):
        Gtk.main_quit(*args)

    # Exit app if abort
    def on_btn_esc_pressed(self, abort):
        Gtk.main_quit(abort)

    # Fill out the form when window1 shows up
    def on_window1_show(self, *args):
        Handler.set_name(self)
        Handler.set_client(self)
        Handler.set_time(self)

    # Prefill
    def set_name(self):
        text_buffer = self.name.get_buffer()
        text_buffer.set_text(Prefill.get_username(), 20)

    def set_client(self):
        text_buffer = self.client.get_buffer()
        text_buffer.set_text(Prefill.get_hostname(), 20)

    def set_time(self):
        text_buffer = self.when.get_buffer()
        text_buffer.set_text(dialog.get_time(), 20)
        '''
    def get_pickle_filepath(self):
        home = dialog.get_userdir()
#        print (home) # Debug entry
        if home:
            pickle_filepath = home + "/.support.pickle"
            return pickle_filepath
        else: return
        '''
    # Get entries        
    def get_name(self):
        name_buffer = self.name.get_text()
        if name_buffer != '':
            return name_buffer
        else:
            dialog.error_message("Du måste ange ett namn.")

    def get_client(self):
        client_buffer = self.client.get_text()
        if client_buffer != '':
            return client_buffer
        else:
            dialog.error_message("Du måste ange vilken dator /skrivare etc. det gäller.\nOm det är en fråga eller förslag, ange ändå vilken dator du sitter på.")
            
    def get_when(self):
        when_buffer = self.when.get_text()
        if when_buffer != '':
            return when_buffer
        else:
            dialog.error_message("Ange vid vilken tidpunkt problemet uppstod.\nOm det är en fråga eller förslag, ange ändå aktuell tid.")
        
    def get_email(self):
        email_buffer = self.email.get_text()
        if email_buffer != '':
            return email_buffer
        else:
            dialog.error_message("Ange en giltig e-postadress för att kunna få svar,\neller kunna följa upp ditt ärende.")

    def get_issue(self):
        if 'issue_buffer' in globals():
            if issue_buffer != '':
                return issue_buffer
            else:
                dialog.error_message("Du måste välja vilken typ av ärende det gäller.")
        else:
            dialog.error_message("Du måste välja vilken typ av ärende det gäller.")
        
    def on_btn_ok_pressed(self, ok):
        if all([(self.get_name()), (self.get_client()), (self.get_when()), (self.get_email()), (self.get_issue())]):
            print (self.get_name())
            print (self.get_client())
            print (self.get_when())
            print (self.get_email())
            print (self.get_issue())
            Gtk.main_quit(ok)
        '''
            # Store data persistently --Not needed if proc comm works..
            # Use pickles instead? Store in mem, not on disk...
            datalist = [(self.get_name()), (self.get_client()), (self.get_when()), (self.get_email()), (self.get_issue())]
            pickle_filepath = self.get_pickle_filepath()
#            print (pickle_filepath) # Debug entry
            with open(pickle_filepath,'wb') as temp_path:
                pickle.dump(datalist, temp_path)
            del datalist
            Gtk.main_quit(ok)
        '''

    def on_cb_issue_changed(self, combo):
        text = combo.get_active_text()
        if text != None:
            global issue_buffer
            issue_buffer = ("%s" %text)
#            print (issue_buffer) # Debug entry
    
    def __init__(self):
        '''Initialization of Handler class.
        
        We use the initialization of the Handler class to establish
        references to the widgets we'll need to work with in the callbacks for
        various signals. This is done using the XML file we created with Glade.
        '''
        # Use GtkBuilder to build our interface from the XML file 
        try:
            builder = Gtk.Builder()
            builder.add_from_file("whoareu.glade") 
        except:
            dialog.error_message("Failed to load UI XML file: whoareu.glade")
            sys.exit(1)        
        
        # get the widgets which will be referenced in callbacks
        self.window1 = builder.get_object("window1")
        self.name = builder.get_object("name")
        self.client = builder.get_object("client")
        self.when = builder.get_object("when")
        self.email = builder.get_object("email")
        
        # connect signals
        builder.connect_signals(self)

    def main(self):
        '''Run main application window.'''
        # Exit app if main win is closed (x:ed). Even if signal from GUI is missing.
        self.window1.connect("delete-event", Gtk.main_quit)
        self.window1.show()
        Gtk.main()
    
if __name__ == "__main__":
    whoareu = Handler()
    whoareu.main()
